/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package asja.formulario;

import asja.dao.LoginDao;
import asja.excecoes.Vazio;
import asja.modelo.LoginModelo;
import asja.outras.Conversoes;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.util.List;

/**
 *
 * @author Alice
 */
public class CadastroLoginFormulario extends JFrame {
    
    
    private JLabel lbl_usuario, lbl_senha;  
    private JTextField jtf_usuario;  
    private JPasswordField pass;    
    private JButton btOK, btCancelar;
    List <LoginModelo> usuarios;
    
    
    
     public CadastroLoginFormulario() 
    {        
        
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        this.setTitle("Cadastro Login");  
        this.setSize(400, 200);          
        this.setLocationRelativeTo(null);  
    } 
     
     public void criaJanela()  
    {     
        
        //criando os objetos
        lbl_usuario = new JLabel(" Usuário "); 
        jtf_usuario = new JTextField("", 20);          
        
        lbl_senha = new JLabel("  Senha  ");  
        pass=new JPasswordField("", 20);      
        
        btOK = new JButton("OK");  
        btOK.setPreferredSize(new Dimension(100,30));        
        
        btCancelar = new JButton("Cancelar");
        btCancelar.setPreferredSize(new Dimension(100,30));
        
        //painel dos botões
        JPanel painel_comandos = new JPanel();  
        painel_comandos.setLayout(new FlowLayout());
        painel_comandos.add(btOK);
        painel_comandos.add(btCancelar);
        
        //painel para rotulo usuario
        JPanel painel_usuario = new JPanel();  
        painel_usuario.setLayout(new FlowLayout());
        painel_usuario.add(lbl_usuario);
        painel_usuario.add(jtf_usuario);
        
        //painel para rotulo senha
        JPanel painel_senha = new JPanel();  
        painel_senha.setLayout(new FlowLayout());
        painel_senha.add(lbl_senha);
        painel_senha.add(pass);
        
        //painel no norte
        JPanel painel_norte = new JPanel();  
        painel_norte.setLayout(new BorderLayout());
        painel_norte.add(painel_usuario, BorderLayout.NORTH);
        painel_norte.add(painel_senha, BorderLayout.SOUTH);
        painel_norte.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Login"));
           
        
        
        //criando o painel principal e adicionando ao JFrame
        JPanel painel_geral = new JPanel();
        this.getContentPane().add(painel_geral);    
        painel_geral.setLayout(new BorderLayout());       
        
        
        //adicionando o painel de comandos ao painel principal, usando o borderLayout.south        
        painel_geral.add(painel_comandos, BorderLayout.SOUTH);
        painel_geral.add(painel_norte, BorderLayout.NORTH);
        
        btOK.addMouseListener(new MouseAdapter() {
        @Override
            public void mouseClicked(MouseEvent evt) {
            
            
                try {
                  
                   compara_usuario();
                    JOptionPane.showMessageDialog(null, "Gravado com sucesso!!!");
                    MenuPrincipalFormulario mnu_principal = new MenuPrincipalFormulario(); 
                    mnu_principal.criajanela_menuprincipal();  
                    mnu_principal.aparencia_MenuPrincipal();
                    dispose(); 
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(CadastroLoginFormulario.this, "Erro!!", "Cadastro Login", JOptionPane.ERROR_MESSAGE);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(CadastroLoginFormulario.this, "Campos vazios ou usário existente!!", "Cadastro Login", JOptionPane.ERROR_MESSAGE);
                }                    
             
            }});
        
        btCancelar.addMouseListener(new MouseAdapter() {
        @Override
            public void mouseClicked(MouseEvent evt) {
            
                int i = 0;
                i= JOptionPane.showConfirmDialog(null, "Tem a certeza que deseja Cancelar?", "Cadastro Login", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (i==0){
                       MenuPrincipalFormulario mnu_principal = new MenuPrincipalFormulario(); 
                       mnu_principal.criajanela_menuprincipal();  
                       mnu_principal.aparencia_MenuPrincipal();
                       dispose(); }                     
                
                       
                    
             
            }});
        
        this.setResizable(false);
        pack();        
        this.setVisible(true);
    
    }
     
     public void cadastro_login() throws Vazio{   
       
 
         try {
            
             LoginModelo in = new LoginModelo();
             Conversoes conv= new Conversoes();
             
             if (jtf_usuario.getText().toString().equals(""))
               throw new Vazio(" Usuario Inválido!");
           else if ((conv.CharParaString(pass.getPassword())).toString().equals(""))
                throw new Vazio(" Senha Inválido!");
             else{                
                 
                 in.setUsuario(jtf_usuario.getText());
                 in.setSenha((conv.CharParaString(pass.getPassword())).toString());
                 LoginDao contr = new LoginDao();
                 contr.adiciona(in);
             }
             
          } catch (SQLException ex) {
             JOptionPane.showMessageDialog(CadastroLoginFormulario.this, "Erro", "Cadastro Login", JOptionPane.ERROR_MESSAGE);

         }
    
    }
     
  public void compara_usuario()throws SQLException, IOException{ 
       
         LoginDao dao= new LoginDao();
         usuarios = dao.pesquisa_usuario(jtf_usuario.getText());
         System.out.println(usuarios);  
         
         if(!(usuarios.isEmpty()))
            throw new IOException(" Usuario Já existe!");
         else     
           cadastro_login();
      
    
  }
   /*  
     public static void main(String[] args){
         CadastroLoginFormulario mnu_log = new CadastroLoginFormulario(); 
         mnu_log.criaJanela();
         
     }*/
    
}
